<template>
  <div class="ai-chat-page" :class="{ 'collapsed': sidebarCollapsed }">
    <!-- Sidebar -->
    <aside class="sidebar" :class="{ 'is-collapsed': sidebarCollapsed }">
      <div class="sidebar-header">
        <div class="title" @click="toggleSidebar" :title="sidebarCollapsed ? '展开' : '收起'">
          <span v-if="!sidebarCollapsed">会话</span>
          <span class="collapse-icon">{{ sidebarCollapsed ? '»' : '«' }}</span>
        </div>
        <el-button v-if="!sidebarCollapsed" size="small" type="primary" :loading="loading.create" @click="createSession">新建</el-button>
      </div>
      <chat-session-list
              :sessions="sessions"
              :current-id="currentSessionId"
              :loading="loading.list"
              :creating="loading.create"
              @select="selectSession"
              @create="createSession"
        @rename="handleRename"
              @delete="onDelete"
              @clear="onClear"
            />
    </aside>
    <!-- Collapse Expander -->
    <div v-if="sidebarCollapsed" class="sidebar-expander">
      <button class="expand-float-btn" @click="toggleSidebar" aria-label="展开会话">
        <span class="icon">»</span>
        <span class="label">展开会话</span>
      </button>
    </div>
    <!-- Main Chat Area -->
    <main class="chat-main" :class="{ empty: !currentSession }">
      <div v-if="currentSession" class="messages-wrapper">
    <chat-message-list
      :messages="messages"
      :streaming="streaming"
      :streaming-buffer="streamingBuffer"
      :input-offset="inputOffset"
      :mode="currentMode"
      :role-label="currentModeLabel"
    />
        <div class="floating-input">
          <chat-input
            :disabled="inputDisabled"
            :sending="loading.send"
            :show-return="showReturn"
            :mode="currentMode"
            :mode-enabled="true"
            @change-mode="changeMode"
            @return="goBackExcerpt"
            @send="sendMessage"
          />
        </div>
      </div>
      <div v-else class="chat-empty"><div class="placeholder">选择或新建一个会话开始对话</div></div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useChatSessions } from '@/composables/useChatSessions'
import ChatSessionList from '@/components/ai/ChatSessionList.vue'
import ChatMessageList from '@/components/ai/ChatMessageList.vue'
import ChatInput from '@/components/ai/ChatInput.vue'

const {
  sessions,
  currentSessionId,
  currentSession,
  messages,
  streaming,
  streamingBuffer,
  loading,
  inputDisabled,
  loadSessions,
  createSession,
  createSessionAndSend,
  selectSession,
  fetchMessages,
  renameSession,
  updateSessionMode,
  deleteSession,
  clearMessages,
  sendMessage,
} = useChatSessions()

loadSessions()
const route = useRoute()
const router = useRouter()

// interpret 引导 + 初始侧栏折叠逻辑
onMounted(async () => {
  // 仅第一次进入时按照当前窗口宽度与指针类型决定初始状态
  try {
    const vw = document.documentElement.clientWidth || window.innerWidth
    const coarse = window.matchMedia && window.matchMedia('(pointer: coarse)').matches
    const narrow = vw < 1100 || (coarse && vw < 1400)
    sidebarCollapsed.value = narrow // 窄界面默认收起，宽界面默认展开
  } catch (e) { /* 忽略 */ }

  if (route.query.interpret) {
    const rawText = route.query.text ? decodeURIComponent(String(route.query.text)) : ''
    const bookTitle = route.query.bt ? decodeURIComponent(String(route.query.bt)) : ''
    const chapter = route.query.chapter
    const sec = route.query.sec
    const para = route.query.para
    const secNum = typeof sec !== 'undefined' ? Number(sec) + 1 : '?'
    const paraNum = typeof para !== 'undefined' ? Number(para) + 1 : '?'
    const template = `请作为古籍研究助手，对以下选段进行结构化解读：\n\n《${bookTitle || '未知典籍'}》 第${chapter}章 第${secNum}节 第${paraNum}段：\n${rawText}\n\n请从：1) 原文释义 2) 关键意象/概念 3) 历史文化背景 4) 思想内涵 5) 现代启示 这几个方面进行。`
    const rawReturn = route.query.return ? decodeURIComponent(String(route.query.return)) : null
    await createSessionAndSend(template, { meta: { purpose: 'interpret', return: rawReturn } })
    router.replace({ name: 'AIChat' })
  }
})

// 会话内联重命名已在 ChatSessionList 内处理
function handleRename(id, title){
  if (!id) return
  renameSession(id, title)
}

// 侧栏折叠
const sidebarCollapsed = ref(false)
function toggleSidebar(){ sidebarCollapsed.value = !sidebarCollapsed.value }

async function onDelete(s){ try { await deleteSession(s.id) } catch(e){} }
async function onClear(s){ try { await clearMessages(s.id) } catch(e){} }
// 移除手动刷新按钮：保留自动流程，如需再次启用可在此处恢复
// function refreshMessages(){ if (currentSessionId.value) fetchMessages(currentSessionId.value) }

// 返回 interpret 来源
function goBackExcerpt(){
  let ret = route.query.return ? decodeURIComponent(String(route.query.return)) : null
  if (!ret && currentSession.value?.meta?.return) {
    ret = currentSession.value.meta.return
    if (ret && /%2F|%3F|%25/.test(ret)) { try { ret = decodeURIComponent(ret) } catch(e){} }
  }
  router.push(ret || '/library')
}

// 是否显示返回按钮
const showReturn = computed(()=>{
  if (!currentSession.value) return false
  if (route.query.return) return true
  return !!currentSession.value.meta?.return
})

// 当前会话角色模式（用于前端展示）
const currentMode = computed(() => {
  const raw = currentSession.value?.meta?.mode
  return raw || 'default'
})

const modeLabelMap = {
  default: '普通助手',
  'role:confucius': '孔子',
  'role:laozi': '老子',
  'role:libai': '李白',
  'role:dufu': '杜甫',
}
const currentModeLabel = computed(() => modeLabelMap[currentMode.value] || '普通助手')

// 切换会话角色 / 模式
async function changeMode(mode){
  if (!currentSession.value || !currentSessionId.value) return
  const cur = currentMode.value
  if (mode === cur) return
  await updateSessionMode(currentSessionId.value, mode)
}

// 滚动到底部（在高度变化或新消息时调用）
function scrollToBottom(){
  requestAnimationFrame(()=>{
    const list = document.querySelector('.chat-message-list')
    if(list) list.scrollTop = list.scrollHeight + 200
  })
}

// 动态为消息列表设置底部可滚动填充，避免移动端输入框或软键盘遮挡
let resizeObserver = null
let viewportListener = null
const inputOffset = ref(170)
function updateInputOffset(el){
  if(!el) return
  const h = el.offsetHeight || 0
  // 使用安全区 + 额外缓冲（24~40px），这里取 36 以兼顾不同浏览器
  const safe = (parseInt(getComputedStyle(document.documentElement).getPropertyValue('env(safe-area-inset-bottom)'))||0)
  const total = h + 36 + safe
  inputOffset.value = total
  document.documentElement.style.setProperty('--input-offset', total + 'px')
}

onMounted(()=>{
  const target = document.querySelector('.floating-input')
  if(target && !resizeObserver){
    updateInputOffset(target)
    resizeObserver = new ResizeObserver(entries => {
      for(const entry of entries){
        updateInputOffset(entry.target)
        scrollToBottom()
      }
    })
    resizeObserver.observe(target)
  }
  // 监听 visualViewport 处理软键盘弹出收起（特别是 iOS Safari）
  if(window.visualViewport){
    viewportListener = () => {
      requestAnimationFrame(()=>{
        updateInputOffset(document.querySelector('.floating-input'))
        scrollToBottom()
      })
    }
    window.visualViewport.addEventListener('resize', viewportListener)
  }
})

onUnmounted(()=>{
  if (resizeObserver){ try { resizeObserver.disconnect() } catch(e){} resizeObserver = null }
  if (window.visualViewport && viewportListener){
    window.visualViewport.removeEventListener('resize', viewportListener)
    viewportListener = null
  }
})
</script>

<style scoped>
/* 全局布局与主题背景（仿古纸+淡金渐变） */
.ai-chat-page { display:flex; height:calc(100vh - 60px); background:linear-gradient(135deg,#ede9e2 0%,#f5f2ec 40%,#efe6d9 100%); transition: all .25s; position:relative; }
@media (max-width:1100px){
  /* 使用动态视口高度减少移动端地址栏变化影响 */
  .ai-chat-page { height:calc(100dvh - 52px); }
}
.ai-chat-page::after { content:''; position:absolute; inset:0; pointer-events:none; background:radial-gradient(circle at 18% 22%,rgba(255,255,255,0.55),transparent 60%),radial-gradient(circle at 82% 68%,rgba(255,255,255,0.45),transparent 65%); mix-blend-mode:overlay; opacity:.75; }

/* 侧栏 */
.sidebar { width:280px; border-right:1px solid rgba(160,140,110,0.25); display:flex; flex-direction:column; background:linear-gradient(150deg,#f8f5ef 0%,#f1ebe2 100%); transition:width .25s ease, opacity .25s; overflow:hidden; backdrop-filter:blur(4px); position:relative; z-index:3; }
.sidebar.is-collapsed { width:0; min-width:0; opacity:0; border:none; pointer-events:none; }
/* 折叠时主区域展开按钮 */
.sidebar-expander { position:absolute; top:14px; left:14px; z-index:7; }
.ai-chat-page.collapsed .sidebar-expander { animation:fadeIn .25s ease; }
.expand-float-btn { position:relative; width:48px; height:48px; display:flex; align-items:center; justify-content:center; border:none; cursor:pointer; background:linear-gradient(135deg,#cfa355,#e2c98a); color:#fff; font-size:20px; font-weight:600; border-radius:16px; box-shadow:0 6px 20px -6px rgba(0,0,0,0.28); transition:.28s; }
.expand-float-btn .icon { transform:rotate(180deg); }
.expand-float-btn:hover { filter:brightness(1.07); transform:translateY(-2px); }
.expand-float-btn:active { filter:brightness(.92); transform:translateY(0); }
.expand-float-btn .label { position:absolute; left:54px; top:50%; transform:translate(4px,-50%); background:linear-gradient(135deg,#fff,#f5efe6); padding:6px 14px; border-radius:14px; font-size:13px; font-weight:600; letter-spacing:.5px; color:#5b4630; white-space:nowrap; border:1px solid rgba(180,150,110,0.35); box-shadow:0 4px 16px -6px rgba(0,0,0,0.25); opacity:0; pointer-events:none; transition:.25s; }
.expand-float-btn:hover .label { opacity:1; transform:translate(8px,-50%); }
@keyframes fadeIn { from { opacity:0; transform:translateY(-4px); } to { opacity:1; transform:translateY(0); } }
.sidebar-header { display:flex; justify-content:space-between; align-items:center; padding:10px 12px 8px; border-bottom:1px solid rgba(180,160,130,0.22); }
.sidebar-header :deep(.el-button){ background:linear-gradient(120deg,#cfa355,#e2c98a); border:none; font-weight:600; letter-spacing:.5px; color:#fff; box-shadow:0 3px 10px -4px rgba(160,120,50,.45); padding:6px 14px; border-radius:18px; transition:.25s; }
.sidebar-header :deep(.el-button:hover){ filter:brightness(1.06); box-shadow:0 4px 14px -4px rgba(160,120,50,.55); }
.sidebar-header :deep(.el-button:active){ filter:brightness(.94); }
.sidebar-header .title { font-weight:600; font-size:14px; display:flex; align-items:center; gap:6px; cursor:pointer; user-select:none; letter-spacing:.5px; }
.collapse-icon { font-size:12px; opacity:.55; }
::v-deep(.sidebar.is-collapsed .sessions-scroll){ display:none; }

/* 主区域 */
.chat-main { flex:1; display:flex; flex-direction:column; background:linear-gradient(180deg,rgba(255,255,255,0.92),rgba(255,255,255,0.82)); backdrop-filter:blur(6px); min-height:0; position:relative; }
.chat-header { display:flex; justify-content:space-between; align-items:center; padding:12px 18px 10px; border-bottom:1px solid rgba(200,180,150,0.28); background:linear-gradient(120deg,rgba(255,255,255,0.85),rgba(255,255,255,0.55)); }
.session-title { display:flex; align-items:center; gap:8px; font-size:15px; font-weight:600; letter-spacing:.5px; color:#5a4324; }
.session-title .name { cursor:text; }
.rename-input { width:220px; }
.model-tag { vertical-align:middle; }
.header-actions { display:flex; gap:4px; }

.chat-empty { flex:1; display:flex; align-items:center; justify-content:center; font-size:14px; color:#665c52; }
.placeholder { padding:20px 30px; background:linear-gradient(135deg,#fbfaf8,#f2ece3); border:1px dashed #d9cdbd; border-radius:10px; }

/* 消息区 */
.messages-wrapper { position:relative; flex:1; display:flex; flex-direction:column; min-height:0; }
::v-deep(.chat-message-list) { background:linear-gradient(180deg,#f7f4ef 0%, #ffffff 120%); }
::v-deep(.chat-message-list){ padding-bottom:calc(var(--input-offset, 170px)); }
::v-deep(.msg.assistant .bubble){ background:#ffffff; border:1px solid #e6ded2; box-shadow:0 2px 6px -2px rgba(0,0,0,0.04); }
::v-deep(.msg.user .bubble){ background:linear-gradient(135deg,#f2f9ef,#e6f4e1); border:1px solid #d4ebcc; }
::v-deep(.msg .avatar){ border-radius:50% !important; background:linear-gradient(135deg,#c99844,#dfc28b); box-shadow:0 2px 6px rgba(180,140,60,0.35); font-weight:500; width:38px; height:38px; }
::v-deep(.msg.user .avatar){ background:linear-gradient(135deg,#67c23a,#95d475); box-shadow:0 2px 6px rgba(103,194,58,0.35); }

/* 浮动输入 */
.floating-input { position:absolute; left:0; right:0; bottom:0; padding:0 24px 18px; }
.floating-input > .chat-input { border-radius:20px; overflow:hidden; box-shadow:0 4px 16px -4px rgba(0,0,0,0.1),0 6px 24px -10px rgba(0,0,0,0.08); backdrop-filter:blur(8px); background:rgba(255,255,255,0.92); border:1px solid rgba(200,180,150,0.35); }
.floating-input .chat-input :deep(textarea){ background:transparent; border-radius:16px; }

/*（刷新按钮已移除）*/
/* 移除旧 expand-btn 样式，此处已用 expand-float-btn */

/* 暗色模式 */
@media (prefers-color-scheme: dark) {
  .ai-chat-page { background:linear-gradient(135deg,#252220,#2d2925 55%,#302a24); }
  .sidebar { background:linear-gradient(150deg,#2e2924,#352f29); border-color:#3c342c; }
  .sidebar-header { border-color:#3c342c; }
  .chat-main { background:linear-gradient(180deg,rgba(46,41,36,0.92),rgba(46,41,36,0.85)); }
  .chat-header { background:linear-gradient(120deg,rgba(60,53,46,0.85),rgba(52,46,40,0.65)); border-color:#4a4036; }
  .session-title { color:#e9ddcf; }
  ::v-deep(.chat-message-list) { background:linear-gradient(180deg,#332e29 0%, #26221e 110%); }
  ::v-deep(.msg.assistant .bubble){ background:#2f2a25; border-color:#463d33; }
  ::v-deep(.msg.user .bubble){ background:#22341f; border-color:#2d472b; }
  .placeholder { background:#2d2722; border-color:#4a4036; color:#cbbfae; }
  .floating-input > .chat-input { background:rgba(60,52,45,0.9); border-color:#5a4a3a; }
  ::v-deep(.msg .avatar){ background:linear-gradient(135deg,#ab813d,#cfb079); }
  .sidebar-expander { top:70px; left:16px; }
  .expand-float-btn { background:linear-gradient(135deg,#b7853e,#d7b06d); }
  .expand-float-btn .label { background:linear-gradient(135deg,#3f362d,#4a4036); color:#e9ddcf; border-color:#5a4a3a; }
  .expand-float-btn:hover .label { box-shadow:0 6px 20px -6px rgba(0,0,0,0.45); }
  /* 刷新按钮已移除 */
}
</style>